package uk.co.caprica.vlcj.oop.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import uk.co.caprica.vlcj.logger.Logger;

/**
 *
 */
public class StreamConsumer implements Runnable {

    /**
     * 
     */
    private static final int IO_BUFFER_SIZE = 1024;
    
    /**
     * 
     */
    private final InputStream inputStream;

    /**
     * 
     */
    private final OutputStream outputStream;
    
    /**
     * 
     * 
     * @param inputStream
     */
    public StreamConsumer(InputStream inputStream, OutputStream outputStream) {
        this.inputStream = inputStream;
        this.outputStream = outputStream;
    }

    @Override
    public final void run() {
        BufferedInputStream in = new BufferedInputStream(inputStream);
        byte[] buff = new byte[IO_BUFFER_SIZE];
        int r;
        try {
            for(;;) {
                r = in.read(buff);
                if(r != -1) {
                    if(outputStream != null) {
                        outputStream.write(buff, 0, r);
                        outputStream.flush();
                    }
                }
                else {
                    break;
                }
            }
        }
        catch(Exception e) {
            Logger.error("Error consuming input stream", e);
        }
        finally {
            try {
                in.close();
            }
            catch(IOException e) {
                Logger.warn("Exception thrown during clean-up", e.getMessage());
            }
        }
    }
}
